package com.jule.miaozhuapc.webSocket.server;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WawaServer {
	
	public static Map<Integer, Socket> socketRooms = new HashMap<>();
	private static Map<String, byte[]> CMD = new HashMap<>();
	private static Map<byte[], String> RETURN = new HashMap<>();

	private static Logger logger = Logger.getLogger(WawaServer.class);


	//GAMEOVERLOCK = false;
	static {
		socketRooms.put(1001, null);
		CMD.put("RESET", new byte[] { (byte) 0xaa, 0x03, 0x01, 0x02, 0x00, (byte) 0xdd });
		CMD.put("COURSE0",
				new byte[] { (byte) 0xaa, 0x08, 0x70, 0x03, 0x01, 0x01, 0x00, 0x01, 0x00, 0x7a, (byte) 0xdd });
		CMD.put("COURSE1",
				new byte[] { (byte) 0xaa, 0x08, 0x01, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x0a, (byte) 0xdd });
		CMD.put("RIGHT", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x04, 0x01, 0x43, (byte) 0xdd });
		CMD.put("LEFT", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x03, 0x01, 0x44, (byte) 0xdd });
		CMD.put("UP", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x02, 0x01, 0x45, (byte) 0xdd });
		CMD.put("DOWN", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x01, 0x01, 0x46, (byte) 0xdd });
		CMD.put("CATCH", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x06, 0x00, 0x40, (byte) 0xdd });

		// CMD.put("RIGHT", new byte[]{ (byte) 0xaa, 0x05, 0x70, 0x33, 0x04, 0x01, 0x43,
		// (byte) 0xdd });
		// CMD.put("LEFT", new byte[]{ (byte) 0xaa, 0x05, 0x70, 0x33, 0x03, 0x01, 0x44,
		// (byte) 0xdd });
		// CMD.put("UP", new byte[]{ (byte) 0xaa, 0x05, 0x70, 0x33, 0x02, 0x01, 0x45,
		// (byte) 0xdd });
		// CMD.put("DOWN", new byte[]{ (byte) 0xaa, 0x05, 0x70, 0x33, 0x01, 0x01, 0x46,
		// (byte) 0xdd });

		CMD.put("RIGHTSTOP", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x04, 0x00, 0x42, (byte) 0xdd });
		CMD.put("LEFTSTOP", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x03, 0x00, 0x45, (byte) 0xdd });
		CMD.put("UPSTOP", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x02, 0x00, 0x44, (byte) 0xdd });
		CMD.put("DOWNSTOP", new byte[] { (byte) 0xaa, 0x05, 0x70, 0x33, 0x01, 0x00, 0x47, (byte) 0xdd });

		// RETURN.put(new byte[]{ (byte) 0xaa, 0x05, 0x46, 0x33, 0x09, 0x01, 0x78,
		// (byte) 0xdd },"AVAILABLE");
		RETURN.put(new byte[] { (byte) 0xaa, 0x05, 0x46, 0x33, 0x09, 0x01, 0x78, (byte) 0xdd }, "SUCCESS");
		RETURN.put(new byte[] { (byte) 0xaa, 0x05, 0x46, 0x33, 0x09, 0x00, 0x79, (byte) 0xdd }, "END");
	}

	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(8888);
		Socket s = null;
		System.out.println("accepting...");
		new Thread(new Test()).start();
		while ((s = ss.accept()) != null) {
			System.out.println("链接主板成功!!");
			socketRooms.put(1001, s);
			new ReceiveThread(s, 1001).start();
		}
		ss.close();
	}

	static class SendCmdThread extends Thread {
		Socket s = null;
		byte[] cmd = null;

		public SendCmdThread(Socket s, byte[] cmd) {
			this.s = s;
			this.cmd = cmd;
		}

		@Override
		public void run() {
			if (s == null || cmd == null || cmd.length == 0) {
				return;
			}
			try {
				Socket socket = s;
				OutputStream os = socket.getOutputStream();
				// String sendInfo = "向服务器发送的数据信息！";
				StringBuffer str = new StringBuffer();
				for (byte b : cmd) {
					str.append(String.format("%02x", b));
					str.append(" ");
				}
				System.out.println("发送原始指令：" + str);
				// byte[] right = { (byte) 0xaa, 0x05, 0x70, 0x33, 0x04, 0x01, 0x43, (byte) 0xdd
				// };
				os.write(cmd, 0, cmd.length);
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static class ReceiveThread extends Thread {
		Socket s = null;
		Integer roomId = null;

		public ReceiveThread(Socket s, Integer roomId) {
			this.s = s;
			this.roomId = roomId;
		}

		@Override
		public void run() {
			try {
				System.out.println("监听主板数据ing");
				Socket socket = s;
				InputStream is = socket.getInputStream();
				List<Byte> input = new ArrayList<Byte>();
				byte[] buff = new byte[1];
				while ((is.read(buff)) > 0) {
					byte b = buff[0];
					input.add(b);
					if (b == (byte) 0xdd) {
						break;
					}
				}
				System.out.println("监听主板数据... len:" + input.size());
				if (input.size() > 1) {
					StringBuffer str = new StringBuffer();
					for (byte b : input) {
						str.append(String.format("%02x", b));
						str.append(" ");
					}
					System.out.println("收到主板数据：[" + str + "]");
					// 判断是否成功
					for (byte[] key : RETURN.keySet()) {
						if (input.size() == key.length) {
							boolean same = false;
							for (int i = 0; i < key.length; i++) {
								if (key[i] != input.get(i)) {
									same = false;
									break;
								} else {
									same = true;
								}
							}
							if (same) {
								System.out.println("游戏结果 = " + same);
								// 游戏结束 回调
								new WawaServerGameOverCallback(roomId,  RETURN.get(key)).GameOver();
							}
						}
					}
				}
				new ReceiveThread(s, roomId).start();
			} catch (Exception e) {
				e.printStackTrace();
				try {
					s.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static String sendCmd(Integer roomId, String cmd) {
		logger.info("收到客户端cmd：" + cmd);
		if (socketRooms.get(roomId) != null) {
			Socket s = socketRooms.get(roomId);
			if (s.isClosed())
				return null;
			if (CMD.get(cmd) == null)
				return null;
			byte[] cmdByte = CMD.get(cmd);
			new SendCmdThread(s, cmdByte).start();
		}else {
			logger.info("找不到" + roomId);
		}
		return null;
	}

}
